package com.bawei.shoppingcar.utils;

import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpUtils {
    /**
     * get请求
     * @param path 网址
     * @return
     */
    public static String doGet(String path) {
        try {
            URL url=new URL(path);
            HttpURLConnection httpURLConnection=(HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.setConnectTimeout(10*1000);
            httpURLConnection.setReadTimeout(10*1000);
            httpURLConnection.connect();
            if(httpURLConnection.getResponseCode()==200)
            {
                InputStream inputStream=httpURLConnection.getInputStream();
                byte[] buffer=new byte[1024];
                int len=0;
                StringBuilder stringBuilder=new StringBuilder();
                while ((len=inputStream.read(buffer))!=-1)
                {
                    stringBuilder.append(new String(buffer,0,len));
                }
                Log.d("TAG", "doGet: "+stringBuilder.toString());
                return  stringBuilder.toString();
            }
        } catch (MalformedURLException e) {   e.printStackTrace();
        } catch (IOException e) {  e.printStackTrace();
        }
        return null;
    }

    /**
     * post请求
     * @param path 网址
     * @param params 请求参数
     * @return
     */
    public static String doPost(String path,String params) {
        try {
            URL url=new URL(path);
            HttpURLConnection httpURLConnection=(HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setConnectTimeout(10*1000);
            httpURLConnection.setReadTimeout(10*1000);
            httpURLConnection.setDoOutput(true);
            httpURLConnection.getOutputStream().write(params.getBytes());
            httpURLConnection.connect();
            if(httpURLConnection.getResponseCode()==200)
            {
                InputStream inputStream=httpURLConnection.getInputStream();
                byte[] buffer=new byte[1024];
                int len=0;
                StringBuilder stringBuilder=new StringBuilder();
                while ((len=inputStream.read(buffer))!=-1)
                {
                    stringBuilder.append(new String(buffer,0,len));
                }
                return  stringBuilder.toString();
            }
        } catch (MalformedURLException e) {   e.printStackTrace();
        } catch (IOException e) {  e.printStackTrace();
        }
        return null;
    }

}
